<template>
    <el-container>
        <el-aside width="200px">
            <h2 class="title">产品类型列表</h2>
            <CategoryTree @selectCategory="selectCategory"></CategoryTree>
        </el-aside>
        <el-main>
            <h2 class="title">{{pageTitle}}商品</h2>
            <!-- title: '',
            price: '',
            num: 0,
            sellPoint: '',
            create_time: false,
            images:'',
            descs: '', -->
            <el-form ref="form" :rules="rules" :model="form" label-width="80px">
                <el-form-item label="商品分类">
                    <span class="category">{{form.category||'请选择商品类别'}}</span>
                    <!-- <el-input v-model="form.name"></el-input> -->
                </el-form-item>
                 <el-form-item label="商品名称" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" prop="price">
                    <el-input v-model="form.price"></el-input>
                </el-form-item>
                <el-form-item  label="商品数量" prop="num">
                    <el-input v-model="form.num"></el-input>
                </el-form-item>
                <el-form-item label="商品卖点"  prop="sellPoint">
                    <el-input v-model="form.sellPoint"></el-input>
                </el-form-item>
                <!-- <el-form-item label="发布时间">
                    <el-col :span="11">
                    <el-date-picker prop="date1" type="date" placeholder="选择日期" v-model="form.date1" style="width: 100%;"></el-date-picker>
                    </el-col>
                    <el-col class="line" prop="date2" :span="1">-</el-col>
                    <el-col :span="11">
                    <el-time-picker placeholder="选择时间" v-model="form.date2" style="width: 100%;"></el-time-picker>
                    </el-col>
                </el-form-item> -->
                 <el-form-item label="商品图片" prop="image">
                    <!-- image -->
                    <UploadGoodImg :fileList="fileList" @getUploadImgUrl="getUploadImgUrl" ref='uploadComponent'></UploadGoodImg>
                   
                </el-form-item>
                <el-form-item label="商品描述" prop="descs">
                    <!-- descs -->
                    <WangEditor ref="WangEditor" @sendWangEditorContent="sendWangEditorContent"></WangEditor>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-show="pageTitle!='查看'" @click="submitForm('form')">立即创建</el-button>
                    <el-button type="warning" v-show="pageTitle!='查看'"  @click="resetForm('form')">重置</el-button>
                    <el-button type="warning" @click="cancelAdd">{{pageTitle==='查看'?'返回':'取消'}}</el-button>
                </el-form-item>
            </el-form>
        </el-main>
    </el-container>
</template>

<script>
import CategoryTree from '@/views/GoodsManage/List/CategoryTree'
import UploadGoodImg from '@/views/GoodsManage/List/UploadGoodImg'
import WangEditor from '@/views/GoodsManage/List/WangEditor'
import { mapState } from 'vuex'
import {SessionUtils} from '@/utils'

export default {
    components:{
        CategoryTree,
        UploadGoodImg,
        WangEditor
    },
    computed:{
      ...mapState('product',['rowData','pageTitle'])
    },
    // created(){
    //   if(this.pageTitle==='编辑'){
    //     console.log('---创建----');
    //     console.log(this.rowData);
    //     this.form=this.rowData;
    //     let arr=JSON.parse(this.rowData.image);
    //     arr.forEach((ele)=>{
    //       this.fileList.push({name:'',url:ele});
    //     })

    //   }
      
    // },
     mounted(){
      if(this.pageTitle==='编辑' || this.pageTitle==='查看'){
        console.log('---创建----',this.rowData);
        // 此时form和rowData指向的地址相同
        this.form=this.rowData;
        let arr=JSON.parse(this.rowData.image);
        this.form.image=arr;
        arr.forEach((ele)=>{
          this.fileList.push({name:'',url:ele});
        })
        this.$nextTick(()=>{
          this.$refs.WangEditor.html=this.rowData.descs;
        })

      }
      
    },
    data() {
      return {
        form: {
          id:'',
          cid:0,
          category:'',
          title: '',
          price: '',
          num: 0,
          sellPoint: '',
          image:[],
          date1:'',
          date2:'',
          create_time: '',
          descs: '',
        },
        rules: {
        title: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          // { min: 3, max: 5, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' },
        ],
        num:[
          {required: true, message: '请输入数量', trigger: 'blur' }
        ]
      },
      fileList:[]
    }
    },
    methods: {
       submitForm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            if(this.pageTitle==='添加'){
              console.log('商品信息',this.form);
              let {title,image,sellPoint,price,cid,category,num,descs}=this.form;
              this.addGoodItem({title,image:JSON.stringify(image),sellPoint,price,cid,category,num,descs});
            }else{
               let {id,title,image,sellPoint,price,cid,category,num,descs}=this.form;
               this.updateGoodItem({id,title,image:JSON.stringify(image),sellPoint,price,cid,category,num,descs});
              // console.log(this.rowData.image);
            }
            
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      async updateGoodItem(params){
        let res=await this.$api.updateGoodItem(params);
        // console.log('编辑商品',res);
        if(res.data.status===200){
           this.$message({
                message: '更新成功',
                type: 'success'
            });
             this.$router.push('/goods/goodlist')
        }else{
            this.$message.error('更新失败');
        }
      },
      async addGoodItem(params){
        let res=await this.$api.addGoodItem(params);
        // console.log(res);
        if(res.data.status===200){
            this.$message({
                message: '添加成功',
                type: 'success'
            });
            this.$router.push('/goods/goodlist')
        }else{
            this.$message.error('添加失败');
        }
      },
      cancelAdd(){
        this.$router.push({name:'goodlist'});
      },
      resetForm(form) {
        if(this.pageTitle==='编辑'){
          this.form=SessionUtils.get('form');
          console.log('reset',SessionUtils.get('form'));
          let arr=JSON.parse(this.form.image);
          this.form.image=arr;
          this.fileList=[];
          arr.forEach((ele)=>{
            this.fileList.push({name:'',url:ele});
          })
          this.$nextTick(()=>{
            this.$refs.WangEditor.html=this.form.descs;
          })
        }else{
           this.$refs[form].resetFields();
          this.$refs.uploadComponent.clear();
          // this.$refs.WangEditor.html='';
          this.$refs.WangEditor.editor.clear();
        }
       
      },
      selectCategory(data){
        console.log('接受到商品类别',data);
        this.form['category']=data.name;
        this.form['cid']=data.cid;
      },
      getUploadImgUrl(imgUrl){
        console.log('receive',imgUrl);
        this.form.image.push(imgUrl);
      },
      sendWangEditorContent(html){
        // console.log('接收到',html);
        this.form.descs=html;
      }
    }
}
</script>

<style lang="less" scoped>
     .el-container{
        margin:15px;
        gap: 15px;
        min-height: 680px;
        .title{
            font-size: 18px;
            font-weight: 400;
            padding: 15px;
        }
     }
     .el-aside {
        background-color: transparent;
        border: 1px solid #ccc;
        color: #333;
        

    }
  
    .el-main {
        padding:0;
        background-color:  transparent;
        border: 1px solid #ccc;
        color: #333;
        .title{
            font-weight: 700;
        }
        .el-form{
            padding:0 15px;
            .category{
                color:skyblue;
                font-size: 16px;
            }
        }
        .input-group{
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: flex-start;
        }
    }
</style>